<template>
  <div class="goods_category_list">
    <el-container>
      <el-header>
        <header-item :item="tips"></header-item>
      </el-header>
      <el-main>
        <main-tools-item :toolsType="toolsType" :searchType="searchType" :inputValue="inputValue" @search='search' @add='add'></main-tools-item>
        <main-spare-item @onClick=''></main-spare-item>
        <main-data-list-item :columns="columns" :dataList="dataList" :pager="page" @batchDelete='batchDelete' @currentChange='currentChange'>
          <el-table-column label="操作" slot="table_oper" min-width="160px">
            <template slot-scope="scope">
              <el-button size="mini" type="success" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </main-data-list-item>
      </el-main>
    </el-container>
    <!--新增弹框 -->
    <el-dialog title="新增" :visible.sync="addDialogVisible" width="30%" :before-close="addBeforeClose" close-on-press-escape close-on-click-modal class="defaultDialog"
      :modal="false">
      <el-form ref="addParam" :rules="addAndEditRules" :model="addParam" label-width="30%">
        <!-- <el-form-item label="类型id">
          <el-input v-model="addParam.id"></el-input>
        </el-form-item> -->
        <el-form-item label="所属分类" prop="pid">
          <el-cascader v-model="addParam.pid" :options="goodsTypeOptions" @change="addTypeSelect" :props="{expandTrigger: 'hover',checkStrictly: true }"
            style="" />
        </el-form-item>
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="addParam.name"></el-input>
        </el-form-item>
        <el-form-item label="类型状态" prop="status">
          <el-select v-model="addParam.status" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        </el-form-item>
        <el-form-item label="类型排序" prop="orderNum">
          <el-input v-model="addParam.orderNum"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-upload class="upload-demo" :action="uploadUrl" :on-preview="addHandlePreview" :on-remove="addHandleRemove" :on-success="addHandleSuccess"
            :file-list="addFileList" list-type="picture" name="file" :limit="1" :headers="uploadHeaders">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="addSumbit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--编辑弹框 -->
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="30%" :before-close="editBeforeClose" close-on-press-escape close-on-click-modal
      class="defaultDialog" :modal="false">
      <el-form ref="editParam" :rules="addAndEditRules" :model="editParam" label-width="30%">
        <!-- <el-form-item label="类型id">
          <el-input v-model="editParam.id"></el-input>
        </el-form-item> -->
        <el-form-item label="所属分类" prop="pid">
          <el-cascader v-model="editParam.pid" :options="goodsTypeOptions" @change="editTypeSelect" :props="{expandTrigger: 'hover',checkStrictly: true }"
            style="" />
        </el-form-item>
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="editParam.name"></el-input>
        </el-form-item>
        <el-form-item label="类型状态" prop="status">
          <el-select v-model="editParam.status" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型排序" prop="orderNum">
          <el-input v-model="editParam.orderNum"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-upload ref="upload" class="upload-demo" :action="uploadUrl" :on-preview="editHandlePreview" :on-remove="editHandleRemove"
            :on-success="editHandleSuccess" :file-list="editFileList" list-type="picture" name="file" :limit="1" :headers="uploadHeaders">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="editSumbit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import {
    get,
    post,
    pat,
    del,
    common,
    getRefresh
  } from "../../../../api/api";
  import headerItem from "./../../Commons/headerItem.vue";
  import mainToolsItem from "./../../Commons/mainToolsItem.vue";
  import mainSpareItem from "./../../Commons/mainSpareItem.vue";
  import mainDataListItem from "./../../Commons/mainDataListItem.vue";
  import config from "../../../../../static/config.js";
  export default {
    components: {
      headerItem,
      mainToolsItem,
      mainSpareItem,
      mainDataListItem
    },
    data() {
      return {
        tips: "商品分类",
        uploadUrl: window.dict.url + "/goods/upFilePic",
        toolsType: 1,
        searchType: 5,
        inputValue: '请输入分类名称',
        sels: [],
        page: {
          pageNo: 1,
          limit: 10,
          sizes: [10, 50, 100],
          total: 0
        },
        columns: [
          // {
          //   prop: 'id',
          //   label: '类型id',
          //   width: '',
          //   align: 'center'
          // },
          // {
          //   prop: 'pid',
          //   label: '类型父类id',
          //   width: '',
          //   align: 'center',
          // },
          {
            prop: 'name',
            label: '类型名称',
            width: '160',
            align: 'center'
          },
          {
            prop: 'icon',
            label: '图标',
            width: '',
            align: 'center'
          },
          {
            prop: 'status',
            label: '类型状态',
            width: '',
            align: 'center'
          },
          {
            prop: 'orderNum',
            label: '类型排序',
            width: '',
            align: 'center'
          },
          {
            prop: 'createUser',
            label: '创建人',
            width: '',
            align: 'center'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: '',
            align: 'center'
          }
        ],
        dataList: [],
        loading: false,
        param: {
          name: '',
          size: '10',
          current: '1'
        },
        addParam: {
          id: '',
          pid: '',
          name: '',
          icon: '',
          status: 1,
          orderNum: '',
        },
        editParam: {
          id: '',
          pid: '',
          name: '',
          icon: '',
          status: '',
          orderNum: '',
        },
        statusOptions: [{
          label: "不可用",
          value: 0
        }, {
          label: "可用",
          value: 1
        }],
        addAndEditRules: {
          // pid: [{
          //   required: true,
          //   message: '请选择分类',
          //   trigger: 'blur'
          // }],
          name: [{
            required: true,
            message: '请输入内容',
            trigger: 'blur'
          }],
          status: [{
            required: true,
            message: '请选择状态',
            trigger: 'blur'
          }]
        },
        goodsTypeOptions: [],
        addDialogVisible: false,
        editDialogVisible: false,
        addFileList: [],
        editFileList: [],
        uploadHeaders: {
          'token': localStorage.getItem('token')
        }
      };
    },
    methods: {
      //--------查询----------
      search(val) {
        this.param ={}
        this.param.name = "";
        this.param.name = val.name;
        this.getGoodsCategoryList();
      },
      //--------新增----------
      addBeforeClose(done) {
        this.addFileList = []
        done()
      },
      add() {
        this.addParam = {
          'status': 1
        }
        this.addDialogVisible = true;
        this.getSecGoodsCategory();
      },
      addSumbit() {
        this.$refs['addParam'].validate(valid => {
          if (valid) {
            this.addDialogVisible = false;
            this.addFileList = []
            this.addGoodsCategory();
          }
        })
      },
      addTypeSelect(val) {
        this.addParam.pid = val[val.length - 1];
      },
      addHandlePreview() {},
      addHandleRemove() {
        this.addParam.icon = " "
      },
      addHandleSuccess(response, file, fileList) {
        this.addParam.icon = response.data
      },
      //--------编辑----------
      editBeforeClose(done) {
        this.editIconFileList = []
        done()
      },
      handleEdit(index, row) {
        this.editFileList.splice(0, 1);
        this.editDialogVisible = true;
        this.editParam.id = row.id;
        this.editParam.pid = row.pid;
        this.editParam.name = row.name;
        this.editParam.status = row.status;
        this.editParam.orderNum = row.orderNum;
        if (row.icon && row.icon != " ") {
          var obj = {}
          this.$set(obj, 'name', row.name)
          this.$set(obj, 'url', row.icon)
          this.editFileList.push(obj)
        }
        this.getSecGoodsCategory();
      },
      editSumbit() {
        this.$refs['editParam'].validate(valid => {
          if (valid) {
            this.editDialogVisible = false;
            this.editGoodsCategory();
          }
        })
      },
      editTypeSelect(val) {
        this.editParam.pid = val[val.length - 1];
      },
      editHandlePreview() {},
      editHandleRemove() {
        this.editParam.icon = " "
      },
      editHandleSuccess(response, file, fileList) {
        this.editParam.icon = response.data
      },
      //--------删除----------
      handleDelete(index, row) {
        this.delConfirm(row.id);
      },
      batchDelete(val) {},
      //-------分页----------
      currentChange(val) {
        this.param.current = "";
        this.param.current = val
        this.getGoodsCategoryList();
      },
      //获取list列表
      getGoodsCategoryList() {
        return new Promise((resolve, reject) => {
          var param = {};
          for (let key in this.param) {
            if (this.param[key] != null && this.param[key].length != 0) {
              param[key] = this.param[key]
            }
          }
          post("/goods/selectGoodsCategory", param).then(resdata => {
            let self = function () {
              this.$router.push({
                path: '/home'
              });
            }.bind(this);
            let error = function () {
              alert(resdata.msg)
            }.bind(this);
            let success = function () {
              if (resdata.code == 1) {
                this.dataList = resdata.data.records;
                this.page.total = resdata.data.total;
              }
            }.bind(this);
            common(self)(error)(success)(resdata);
            resolve();
          });
        });
      },
      getSecGoodsCategory() {
        return new Promise((resolve, reject) => {
          get("/goods/secGoodsCategory").then(resdata => {
            let self = function () {
              this.$router.push({
                path: '/home'
              });
            }.bind(this);
            let error = function () {
              alert(resdata.msg)
            }.bind(this);
            let success = function () {
              if (resdata.code == 1) {
                var list = resdata.data;
                var newList = [];
                const getStr = function (list, newList) {
                  for (var i = 0; i < list.length; i++) {
                    var midList = {};
                    midList.value = list[i].id;
                    midList.label = list[i].name;
                    if (list[i].goodsCategoryList) {
                      midList.children = [];
                      newList[i] = midList;
                      getStr(list[i].goodsCategoryList, newList[i].children)
                    }
                    newList[i] = midList;
                  }
                }
                getStr(list, newList)
                this.goodsTypeOptions = newList;
              }
            }.bind(this);
            common(self)(error)(success)(resdata);
            resolve();
          });
        });
      },
      addGoodsCategory() {
        return new Promise((resolve, reject) => {
          console.log(this.addParam)
          var addParam = {};
          for (let key in this.addParam) {
            if (this.addParam[key] != null && this.addParam[key].length != 0) {
              addParam[key] = this.addParam[key]
            }
          }
          post("/goods/addGoodsCategory", addParam).then(resdata => {
            let self = function () {
              this.$router.push({
                path: '/home'
              });
            }.bind(this);
            let error = function () {
              alert(resdata.msg)
            }.bind(this);
            let success = function () {
              if (resdata.code == 1) {
                this.$message({
                  message: '新增成功！',
                  type: 'success',
                  duration: 2000,
                });
                this.getGoodsCategoryList();
              }
            }.bind(this);
            common(self)(error)(success)(resdata);
            resolve();
          });
        });
      },
      editGoodsCategory() {
        return new Promise((resolve, reject) => {
          var editParam = {};
          for (let key in this.editParam) {
            if (this.editParam[key] != null && this.editParam[key].length != 0) {
              editParam[key] = this.editParam[key]
            }
          }
          post("/goods/updateGoodsCategory", editParam).then(resdata => {
            let self = function () {
              this.$router.push({
                path: '/home'
              });
            }.bind(this);
            let error = function () {
              alert(resdata.msg)
            }.bind(this);
            let success = function () {
              if (resdata.code == 1) {
                this.$message({
                  message: '编辑成功！',
                  type: 'success',
                  duration: 2000,
                });
                this.getGoodsCategoryList();
              }
            }.bind(this);
            common(self)(error)(success)(resdata);
            resolve();
          });
        });
      },
      delConfirm(id) {
        this.$confirm('确定删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.delGoodsCategory(id);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      delGoodsCategory(id) {
        return new Promise((resolve, reject) => {
          post("/goods/delGoodsCategory", {
            'id': id
          }).then(resdata => {
            let self = function () {
              this.$router.push({
                path: '/home'
              });
            }.bind(this);
            let error = function () {
              alert(resdata.msg)
            }.bind(this);
            let success = function () {
              if (resdata.code == 1) {
                this.$message({
                  message: '删除成功！',
                  type: 'success',
                  duration: 2000,
                });
                this.getGoodsCategoryList();
              }
            }.bind(this);
            common(self)(error)(success)(resdata);
            resolve();
          });
        });
      }
    },
    async mounted() {
      await this.getGoodsCategoryList();
    },
    watch: {}
  };

</script>

<style lang="scss">
  .goods_category_list {
    background-color: white;
    font-size: 1.8rem;
    width: 100%;
    height: 100%;
    .el-container {
      height: 100%;
      .el-header,
      .el-footer {
        background-color: #F9FAFE;
        color: #333;
        text-align: center;
        line-height: 50px;
        height: 50px !important;
        .header-child {
          height: 50px;
          width: 100%;
          text-align: left;
          padding-left: 20px;
          background-color: #cbe9eb;
          border-bottom: 1px solid black;
          box-shadow: 0 5px 5px 0 rgba(0, 0, 0, 0.5);
        }
      }
      .el-main {
        box-shadow: 0 5px 5px 0px rgba(0, 0, 0, 0.5); // margin: 10px 20px;
        margin: 10px;
        background-color: #fff;
        color: #333;
        text-align: center;
        height: 100%;
      }
    }
    /* 弹框CSS*/
    .defaultDialog {
      z-index: 1200 !important;
      .el-dialog {
        box-shadow: 0px 5px 15px 0 rgba(0, 0, 0, 0.5);
        border-radius: 5px;
        width: 50% !important;
        .el-dialog__header {
          text-align: left;
          .el-dialog__title {
            font-family: "Roboto", sans-serif;
            color: #7d7d7d;
            font-size: 15px;
          }
        }
        .el-dialog__body {
          .el-form {
            padding-left: 40px;
            .el-form-item {
              width: 100%;
              .el-form-item__content {
                text-align: left;
                width: 250px;
                .el-cascader {
                  width: 100%;
                }
                .el-select {
                  width: 100%;
                }
              }
              .el-form-item__label {
                padding: 0 50px 0 0;
                min-width: 80px;
                color: #333;
                font-weight: 400;
                font-size: 13px;
              }
            }
          }
        }
      }
    }
  }

</style>
